import request from '@/utils/request'
import upload from '@/utils/upload.js'
// 选择图片
export const chooseImage = () => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			extension: ['png', 'jpg', 'jpeg', 'gif'],
			success: (res) => {
				// compress_by_cancas(res.tempFilePaths[0]).then((ret) => {
				resolve(res.tempFilePaths[0])
				// })
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}
// 图片压缩
export const compress_by_cancas = (src) => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src,
			success: (res) => {
				// 图片原始长宽
				let canvasWidth = res.width;
				let canvasHeight = res.height;
				let base = canvasWidth / canvasHeight;
				if (canvasWidth > 400) {
					canvasWidth = 400;
					canvasHeight = Math.floor(canvasWidth / base);
				}
				let img = new Image();
				img.src = src; // 要压缩的图片
				let canvas = document.createElement('canvas');
				let ctx = canvas.getContext('2d');
				canvas.width = canvasWidth;
				canvas.height = canvasHeight;

				//  将图片画到canvas上面   使用Canvas压缩
				ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
				resolve(canvas.toDataURL('image/png'))
			}
		})
	})
}
// 上传文件
export const uploadFile = (filePath, formData) => {
	return upload({
		url: '/truckDriver/uploadPic',
		filePath,
		formData,
		timeout: 180 * 1000
	})
}

// 识别文件(阿里云)
export const uploadFiles = (filePath, formData) => {
	return upload({
		url: '/truckDriver/identifyCertificate',
		filePath,
		formData,
		timeout: 180 * 1000
	})
}

// 查看文件
export const getImage = (ids) => {
	return request({
		url: '/truckDriver/picview?fileId=' + ids,
		method: 'get'
	})
}